package com.iot08.api.utils.request;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iot08.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.bson.types.ObjectId;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @version 1.0
 * @Description: 请求参数特殊处理
 * @time: 2020/11/19 18:30
 * @author: Rock
 */
@Slf4j
public class ParamHandle {

    /**
     * 解析参数query内查询条目
     *
     * @param paramValue
     * @param query
     * @time: 2020/11/19 18:50
     * @author: Rock
     * @version 1.0
     */
    public static void queryParamHandle(Document query, String paramValue) {
        if (StringUtil.isNotBlank(paramValue)) {
            JSONObject json = JSON.parseObject(paramValue);
            JSONObject data = json.getJSONObject("id");
            if (data != null) {
                Document sub = new Document();
                for (Map.Entry<String, Object> entry : data.entrySet()) {
                    if (StringUtil.isNotBlank(entry.getValue()) && ObjectId.isValid(entry.getValue().toString())) {
                        sub.put("$" + entry.getKey(), new ObjectId(entry.getValue().toString()));
                    } else {
                        sub.put("$" + entry.getKey(), entry.getValue().toString());
                    }
                }
                query.put("_id", sub);
            }
            data = json.getJSONObject("timestamp");
            if (data != null) {
                Document sub = new Document();
                for (Map.Entry<String, Object> entry : data.entrySet()) {
                    try {
                        if (StringUtil.isNotBlank(entry.getValue())) {
                            sub.put("$" + entry.getKey(), Double.parseDouble(entry.getValue().toString()));
                        }
                    } catch (Exception e) {
                        //这里需捕获处理掉
                        log.error("query timestamp is exception. query = {}", paramValue);
                        e.printStackTrace();
                    }
                }
                query.put("t", sub);
            }
        }
    }

    /**
     * @param request
     * @time: 2021/3/6 17:39
     * @author: Rock
     * @version 1.0
     */
    public static Map<String, Object> getParam(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        BufferedReader br;
        try {
            br = request.getReader();
            String str, wholeStr = "";
            while ((str = br.readLine()) != null) {
                wholeStr += str;
            }
            if (StringUtil.isNotBlank(wholeStr)) {
                params = JSON.parseObject(wholeStr, Map.class);
            }
        } catch (IOException e1) {
            log.error("getParam exception={}", e1.getMessage());
        }
        return params;
    }

    /**
     * @param request
     * @time: 2021/5/12 10:28
     * @author: Rock
     * @version 1.0
     */
    public static Map<String, String> getRequestParams(HttpServletRequest request) {
        Map<String, String[]> requestParams = request.getParameterMap();
        Map<String, String> params = new HashMap<>(requestParams.size());
        for (Iterator<String> iterator = requestParams.keySet().iterator(); iterator.hasNext(); ) {
            String name = iterator.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return params;
    }

}
